import React, { PropsWithChildren, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router-dom';
import { Button, Descriptions, Alert, message, Upload } from 'antd';
import { AxiosError } from 'axios';
import { CombinedState } from '../../store/reducers';
import actions from '../../store/actions/profile';
import './style.less';
import { LOGIN_TYPES } from '../../store/action-types';
import { ProfileState } from '@/store/reducers/profile';
import NavHeader from '@/components/NavHeader';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof actions;

interface Params {}

type RouteProps = RouteComponentProps<Params>;
type Props = PropsWithChildren<StateProps & DispatchProps & RouteProps>;

function beforeUpload(file: any) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('你只能上传JPG/PNG 文件!');
  }
  const isLessThan2M = file.size / 1024 / 1024 < 2;
  if (!isLessThan2M) {
    message.error('图片必须小于2MB!');
  }
  return isJpgOrPng && isLessThan2M;
}

function Profile(props: Props) {
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    props.validate().catch((error: AxiosError) => message.error(error.message));
  }, []);
  const logout = () => {
    props.logout();
  };

  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
    } else if (info.file.status === 'done') {
      let { success, data, message } = info.file.response;
      if (success) {
        setLoading(false);
        // props.changeAvatar(data);
      } else {
        message.error(message);
      }
    }
  };

  let content;
  if (props.loginState === LOGIN_TYPES.UN_VALIDATE) {
    content = null;
  } else if (props.loginState === LOGIN_TYPES.LOGINED) {
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <UploadOutlined />}
        <div className="ant-upload-text">上传</div>
      </div>
    );

    content = (
      <div className="user-info">
        <Descriptions title="当前登录用户">
          <Descriptions.Item label="用户名">{props.user.username}</Descriptions.Item>
          <Descriptions.Item label="手机号">{props.user.username}</Descriptions.Item>
          <Descriptions.Item label="邮箱">{props.user.email}</Descriptions.Item>
          <Descriptions.Item label="头像">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://localhost:8000/user/uploadAvatar"
              data={{ userId: props.user.id }}
              onChange={handleChange}
              beforeUpload={beforeUpload}
            ></Upload>
          </Descriptions.Item>
        </Descriptions>
        <Button type="primary" onClick={logout}>
          退出登录
        </Button>
      </div>
    );
  } else {
    // 没有登录
    content = (
      <>
        <Alert
          type="warning"
          message="当前未登录"
          description="亲爱的用户你好，你当前尚未登录，请你选择注册或者登录"
        />
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Button
            type="dashed"
            style={{ marginRight: '20px' }}
            onClick={() => props.history.push('/login')}
          >
            登录
          </Button>
          <Button type="dashed" onClick={() => props.history.push('/register')}>
            注册
          </Button>
        </div>
      </>
    );
  }

  return (
    <section>
      <NavHeader history={props.history}>个人中心</NavHeader>
      {content}
    </section>
  );
}

let mapStateToProps = (state: CombinedState): ProfileState => state.profile;

export default connect(mapStateToProps, actions)(Profile);
